﻿using System;
using System.Data;

namespace VitCode.Castle.Helper
{
    /// <summary>
    /// 数据库参数缓冲
    /// </summary>
    public sealed class ParameterCache
    {
        private readonly NameObjectDictionary m_SqlCollection;

        /// <summary>
        /// 
        /// </summary>
        public ParameterCache()
        {
            m_SqlCollection = new NameObjectDictionary();
        }

        /// <summary>
        /// 
        /// </summary>
        public IDbDataParameter this[string sql, string paramName]
        {
            set
            {
                var paCache = m_SqlCollection[sql] as NameObjectDictionary;
                if (paCache == null)
                {
                    paCache = new NameObjectDictionary();
                    m_SqlCollection[sql] = paCache;
                }
                paCache[paramName] = value;
            }
            get
            {
                var paCache = m_SqlCollection[sql] as NameObjectDictionary;
                if (paCache != null)
                {
                    return (IDbDataParameter) paCache[paramName];
                }
                return null;
            }
        }

        /// <summary>
        /// 设定关于Sql的缓冲
        /// </summary>
        public IDbDataParameter this[string sql]
        {
            set
            {
                var paCache = m_SqlCollection[sql] as NameObjectDictionary;
                if (paCache == null)
                {
                    paCache = new NameObjectDictionary();
                    m_SqlCollection[sql] = paCache;
                }
                if (value == null)
                    throw new ArgumentNullException(null, "输入的IDbDataParameter不能为空");
                paCache[value.ParameterName] = value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public IDbDataParameter[] GetDataParameters(string sql)
        {
            var paCache = m_SqlCollection[sql] as NameObjectDictionary;
            if (paCache != null)
            {
                var result = new IDbDataParameter[paCache.Values.Length];
                paCache.Values.CopyTo(result, 0);
                return result;
            }
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        public void Clear()
        {
            m_SqlCollection.Clear();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sql"></param>
        public void Clear(string sql)
        {
            var paCache = m_SqlCollection[sql] as NameObjectDictionary;
            if (paCache != null) paCache.Clear();
        }
    }
}
